<?php


/**
 * Контроллер проэктов для админки.
 */
class ProjectsController extends Zend_Controller_Action
{

    const NEWS_PER_PAGE = 10;

    /**
     * FlashMessenger
     *
     * @var Lib_Flash
     */
    protected $_flashMessenger = null;

    function init()
    {
        $usersession = new \Zend_Session_Namespace("usersession");


                       if (!($usersession->general=="generalisimus")){

                           $this->_redirect('/getin');
                       }

        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayotu();
        }

        $this->_helper->layout()->setLayout('admin-layout');

        $this->_flashMessenger = new Lib_Flash();
    }


    function indexAction()
    {

        $page = intval($this->_request->getParam('page', 1));

        $offset = $page > 0 ? ($page - 1) * self::NEWS_PER_PAGE : 0;

        $newsManager = new \Managers\Projects();
        $projects = $newsManager->getList(self::NEWS_PER_PAGE, $offset, null);
        $total = $newsManager->getTotalRecords();
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($total));
        $paginator->setCurrentPageNumber($page);
        $paginator->setItemCountPerPage(self::NEWS_PER_PAGE);

        $this->view->projects = $projects;
        $this->view->paginator = $paginator;
    }

    function editAction()
    {
        $id = $this->_request->getParam('id');
        $prManager = new \Managers\Projects();
        $record = $prManager->getById($id);

        $form = new App_Form_News_Form();
        $form->isValid($record);
        if (!$record) {
            $this->_flashMessenger->addMessage('Project does not exist.', Lib_Flash::ERROR, Lib_Flash::LATER);
            $this->_redirect('/projects');
        }

        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            if ($form->isValid($params)) {
                try {
                    $form->img->receive();

                    $object = $prManager->update($params['id'], $params['title'], $params['content'], $params['public']);
                    $file_path = $form->img->getFileName();
                    $img_value = $form->img->getValue();
                    if (!empty($img_value)) {
                        $image_url = $this->getImageUrl($object->getId(), $file_path);
                        $prManager->resizer('unused', dirname(APPLICATION_PATH) . '/public' . $image_url, $file_path, 250);
                        $prManager->setImage($object->getId(), $image_url);
                    }

                    if ($params['public']) {
                        $this->_flashMessenger->addMessage('Project successfully updated.', Lib_Flash::NOTICE, Lib_Flash::LATER);
                        $this->_redirect('/projects');
                    } else {
                        $this->_redirect("/projects/preview/id/{$object->getId()}");
                    }
                } catch (Exception $e) {
                    $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::NOW);
                }
            }
        }
        $this->view->project = $record;
        $this->view->form = $form;
    }

    function addAction()
    {
        $form = new App_Form_News_Form();

        if ($this->_request->isPost())
        {
            $params = $this->_request->getParams();

            if ($form->isValid($params)) {
      try {
                    $form->img->receive();
                    $prManager = new \Managers\Projects();
                    $object = $prManager->add($params['title'], $params['content'],$params['public']);
                    $file_path = $form->img->getFileName();
                    $img_value = $form->img->getValue();
                    if (!empty($img_value)) {
                        $image_url = $this->getImageUrl($object->getId(), $file_path);
                        $prManager->resizer('unused', dirname(APPLICATION_PATH) . '/public' . $image_url, $file_path, 250);
                        $prManager->setImage($object->getId(), $image_url);
                    }
//                    print_r($file_path); die;
                    if ($params['public'])
                    {
                        $this->_flashMessenger->addMessage('Project successfully added.', Lib_Flash::NOTICE, Lib_Flash::LATER);
                        $this->_redirect('/projects');
                    } else { $this->_redirect("/projects/preview/id/{$object->getId()}");}
             }
        catch (Exception $e)
            {
                    $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::NOW);
                }
            }
        }

        $this->view->form = $form;

    }

    function previewAction()
    {
        $id = $this->_request->getParam('id');
        $prManager = new \Managers\Projects();
        $project = $prManager->getById($id);

        if (!$project) {
            $this->_flashMessenger->addMessage('Project does not exist.', Lib_Flash::ERROR, Lib_Flash::LATER);
            $this->_redirect('/projects');
        }
        $this->_helper->layout()->setLayout('build-layout2');
        $this->view->project = $project;
        $projManager=new Managers\Projects();
        $projects=$projManager->getList(3,0,1);
        $this->view->projects=$projects;
    }

    function postAction()
    {
        $id = $this->_request->getParam('id');
        $prManager = new \Managers\Projects();
        $result = $prManager->setPosted(    $id);
        if ($result) {
            $this->_flashMessenger->addMessage('Project successfully posted.', Lib_Flash::NOTICE, Lib_Flash::LATER);
        } else {
            $this->_flashMessenger->addMessage('Project does not exist', Lib_Flash::ERROR, Lib_Flash::LATER);
        }
        $this->_redirect('/projects');
    }

    function deleteAction() {
        $id = $this->_request->getParam('id');
        $prManager = new \Managers\Projects();
        $result = $prManager->delete($id);
        if($result) {
            $this->_flashMessenger->addMessage('Project successfully deleted.', Lib_Flash::NOTICE, Lib_Flash::LATER);
        } else {
            $this->_flashMessenger->addMessage('Project does not exist.', Lib_Flash::ERROR, Lib_Flash::LATER);
        }
        $this->_redirect('/projects');
    }

   
    /**
     * Возвращает адрес картинки для новости.
     * @param $id
     * @param $file_path путь к загруженному файлу.
     * @return string путь к файлу для хранения в базе (относительно папки public)
     */
    private function getImageUrl($id, $file_path)
    {
        $prefix = '/images/projects/';

        $new_name = $id . substr(md5(time()), 0, 6);
        $ext = pathinfo($file_path, PATHINFO_EXTENSION);

        $result = preg_replace('/\/{2,}/', '/', $prefix . $new_name . '.' . $ext);
        return $result;
    }
         private function getImageUrlForGallery($id, $file_path)
    {
        $prefix = '/images/photos/';

        $new_name = $id . substr(md5(time()), 0, 6);
        $ext = pathinfo($file_path, PATHINFO_EXTENSION);

        $result = preg_replace('/\/{2,}/', '/', $prefix . $new_name . '.' . $ext);
        return $result;
    }
}

